/**
 * 
 */
package ca.lscs.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ca.lscs.web.utils.SessionUtils;

/**
 * @author steve
 *
 */
public class AuthFilter implements Filter {

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#destroy()
	 */
	@Override
	public void destroy() {
		//nothing to destroy
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletResponse hResponse = (HttpServletResponse)response;
		HttpServletRequest hRequest = (HttpServletRequest)request;
		try {
			HttpSession session = hRequest.getSession(true);
			SessionUtils.getUserSession(session);
		} catch(InvalidSessionException e) {
			if(!hRequest.getRequestURI().equals("/login")) {
				hResponse.sendRedirect("/login");
				return;
			}
		}
		chain.doFilter(request, response);
	}

	/* (non-Javadoc)
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	@Override
	public void init(FilterConfig config) throws ServletException {
		//nothing to init
	}

}
